<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--类别数据 --左侧树   -->
      <el-col :span="4" :xs="24">
        <div class="head-containder">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAdd"
                  v-hasPermi="['keyfigure:category:add']"
              >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                  type="success"
                  plain
                  icon="Edit"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['keyfigure:category:edit']"
              >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                  type="danger"
                  plain
                  icon="Delete"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['keyfigure:category:remove']"
              >删除
              </el-button>
            </el-col>
          </el-row>
        </div>
        <div class="head-container">
          <el-input
              v-model="categoryName"
              placeholder="请输入期间类型名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="tree-container">
          <el-tree
              :data="categoryOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="categoryTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"

          >

          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form ref="categoryRef" :model="form" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="id" prop="id" v-if="false">
            <el-input v-model="form.id" placeholder="请输入期间类型id"/>
          </el-form-item>
          <el-form-item label="期间类型" label-width="100px" prop="type">
            <el-select v-model="form.type" style="width: 200px">
              <el-option label="年" value="0"/>
              <el-option label="季" value="1"/>
              <el-option label="月" value="2"/>
              <el-option label="周" value="3"/>
              <el-option label="日" value="4"/>
            </el-select>
          </el-form-item>

          <el-form-item label="父项id" label-width="100px" v-if="false" prop="parentId">
            <el-input v-model="form.parentId" placeholder="请输入父项期间类型"/>
          </el-form-item>
          <el-form-item label="父项期间类型" label-width="100px" prop="parentName">
            <el-input v-model="form.parentName" placeholder="请输入父项期间类型" readonly/>
          </el-form-item>
          <el-form-item label="期间类型编码" label-width="100px" prop="code" :show-overflow-tooltip="true">
            <el-input v-model="form.code" placeholder="请输入期间类型编码"/>
          </el-form-item>
          <el-form-item label="期间类型名称" label-width="100px" prop="name" :show-overflow-tooltip="true">
            <el-input v-model="form.name" placeholder="请输入期间类型名称"/>
          </el-form-item>
          <el-form-item label="开始时间" label-width="100px" prop="startTime" :show-overflow-tooltip="true">
            <el-date-picker
                v-model="form.startTime"
                type="date"
                placeholder="请选择日期"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" label-width="100px" prop="endTime" :show-overflow-tooltip="true">
            <el-date-picker
                v-model="form.endTime"
                type="date"
                placeholder="请选择日期"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="频次" label-width="100px" prop="frequency" :show-overflow-tooltip="true">
            <el-input-number v-model="form.frequency" :min="1" :max="30" placeholder="请输入频次"/>
          </el-form-item>
        </el-form>
        <el-divider content-position="center">时格</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Edit"
                @click="generatePeriodSlot"
                v-hasPermi="['keyfigure:template:add']"
            >生成时格
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table class="table-container" v-loading="loading"
                  stripe
                  :data="categoryAndParamList"
                  :span-method="spanMethod"
                  :header-cell-style="{'border-right':'1px solid #EEEEEE'}"
                  :cell-style="{'border-right':'1px solid #EEEEEE'}"
                  :expand-row-keys="expandedRows"
                  row-key="index"
                  ref="categoryTableRef"
                  @selection-change="handleSelectionChange"
                  @row-click="handleRowClick"
                  :row-class-name="iconHadler"
                  :show-overflow-tooltip='true'
                  border
        >
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column label="id" v-if="false" prop="id" width="150"/>
          <el-table-column label="时格名称" prop="name" width="150"/>
          <el-table-column label="开始时间" prop="startTime" width="150"/>
          <el-table-column label="结束时间" prop="endTime" width="150"/>
          <el-table-column label="操作" align="center" :inline="true" class-name="small-padding fixed-width">
            <template #default="scope">
              <template>
                <el-button link type="primary" icon="Edit" @click="handleChangeVersionParam(scope.row)"
                           v-hasPermi="['keyfigure:param:edit']">编辑
                </el-button>
              </template>
            </template>
          </el-table-column>

        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getCategoryAndParamList"
        />
      </el-col>
    </el-row>


    <!-- 添加或修改参数模板对话框 -->
    <el-dialog :title="title" v-model="open" width="750px" append-to-body>
      <el-form ref="templateRef" :model="periodForm" :inline="true" :rules="rules" label-width="100px">
        <el-form-item label="id" prop="id" v-if="false">
          <el-input v-model="periodForm.id" placeholder="请输入期间类型id"/>
        </el-form-item>
        <el-form-item label="期间类型" label-width="100px" prop="type">
          <el-select v-model="periodForm.type" style="width: 200px">
            <el-option label="年" value="0"/>
            <el-option label="季" value="1"/>
            <el-option label="月" value="2"/>
            <el-option label="周" value="3"/>
            <el-option label="日" value="4"/>
          </el-select>
        </el-form-item>

        <el-form-item label="父项id" label-width="100px" v-if="false" prop="parentId">
          <el-input v-model="periodForm.parentId" placeholder="请输入父项期间类型"/>
        </el-form-item>
        <el-form-item label="父项期间类型" label-width="100px" prop="parentName">
          <el-input v-model="periodForm.parentName" placeholder="请输入父项期间类型" readonly/>
        </el-form-item>
        <el-form-item label="期间类型编码" label-width="100px" prop="code" :show-overflow-tooltip="true">
          <el-input v-model="periodForm.code" placeholder="请输入期间类型编码"/>
        </el-form-item>
        <el-form-item label="期间类型名称" label-width="100px" prop="name" :show-overflow-tooltip="true">
          <el-input v-model="periodForm.name" placeholder="请输入期间类型名称"/>
        </el-form-item>
        <el-form-item label="开始时间" label-width="100px" prop="startTime" :show-overflow-tooltip="true">
          <el-date-picker
              v-model="periodForm.startTime"
              type="date"
              placeholder="请选择日期"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" label-width="100px" prop="endTime" :show-overflow-tooltip="true">
          <el-date-picker
              v-model="periodForm.endTime"
              type="date"
              placeholder="请选择日期"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="频次" label-width="100px" prop="frequency" :show-overflow-tooltip="true">
          <el-input-number v-model="periodForm.frequency" :min="1" :max="30" placeholder="请输入频次"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup name="periodType">

const {proxy} = getCurrentInstance();
const title = ref("");
const selectTree = ref("");
const categoryOptions = ref([
  {
    "id": 100,
    "label": "自然年",
    "type": "0",
    "parentId": "",
    "parentName": "",
    "code": "PT100",
    "name": "自然年",
    "startTime": "2019-01-01",
    "endTime": "2024-12-31",
    "frequency": "1",
    "periodSlotList": [
      {
        "name": "2019",
        "startTime": "2019-01-01",
        "endTime": "2019-12-31"
      },
      {
        "name": "2020",
        "startTime": "2020-01-01",
        "endTime": "2020-12-31"
      },
      {
        "name": "2021",
        "startTime": "2021-01-01",
        "endTime": "2021-12-31"
      },
      {
        "name": "2022",
        "startTime": "2022-01-01",
        "endTime": "2022-12-31"
      },
      {
        "name": "2023",
        "startTime": "2023-01-01",
        "endTime": "2023-12-31"
      },
      {
        "name": "2024",
        "startTime": "2024-01-01",
        "endTime": "2024-12-31"
      }
    ],
    "children": [
      {
        "id": 101,
        "label": "自然季",
        "type": "1",
        "parentId": "100",
        "parentName": "自然年",
        "code": "PT1001",
        "name": "自然季",
        "startTime": "2019-01-01",
        "endTime": "2024-12-31",
        "frequency": "1",
        "periodSlotList": [
          {
            "name": "2019Q1",
            "startTime": "2019-01-01",
            "endTime": "2019-03-31"
          },
          {
            "name": "2019Q2",
            "startTime": "2019-04-01",
            "endTime": "2019-05-31"
          },
          {
            "name": "2019Q3",
            "startTime": "2019-07-01",
            "endTime": "2019-09-30"
          },
          {
            "name": "2019Q4",
            "startTime": "2019-10-01",
            "endTime": "2019-12-31"
          },
          {
            "name": "2020Q1",
            "startTime": "2020-01-01",
            "endTime": "2020-03-31"
          },
          {
            "name": "2020Q2",
            "startTime": "2020-04-01",
            "endTime": "2020-05-31"
          },
          {
            "name": "2020Q3",
            "startTime": "2020-07-01",
            "endTime": "2020-09-30"
          },
          {
            "name": "2020Q4",
            "startTime": "2020-10-01",
            "endTime": "2020-12-31"
          },
          {
            "name": "2021Q1",
            "startTime": "2021-01-01",
            "endTime": "2021-03-31"
          },
          {
            "name": "2021Q2",
            "startTime": "2021-04-01",
            "endTime": "2021-05-31"
          },
          {
            "name": "2021Q3",
            "startTime": "2021-07-01",
            "endTime": "2021-09-30"
          },
          {
            "name": "2021Q4",
            "startTime": "2021-10-01",
            "endTime": "2021-12-31"
          },
          {
            "name": "2022Q1",
            "startTime": "2022-01-01",
            "endTime": "2022-03-31"
          },
          {
            "name": "2022Q2",
            "startTime": "2022-04-01",
            "endTime": "2022-05-31"
          },
          {
            "name": "2022Q3",
            "startTime": "2022-07-01",
            "endTime": "2022-09-30"
          },
          {
            "name": "2022Q4",
            "startTime": "2022-10-01",
            "endTime": "2022-12-31"
          },
          {
            "name": "2023Q1",
            "startTime": "2022-01-01",
            "endTime": "2023-03-31"
          },
          {
            "name": "2023Q2",
            "startTime": "2023-04-01",
            "endTime": "2023-05-31"
          },
          {
            "name": "2023Q3",
            "startTime": "2023-07-01",
            "endTime": "2023-09-30"
          },
          {
            "name": "2023Q4",
            "startTime": "2023-10-01",
            "endTime": "2023-12-31"
          },
          {
            "name": "2024Q1",
            "startTime": "2024-01-01",
            "endTime": "2024-03-31"
          },
          {
            "name": "2024Q2",
            "startTime": "2024-04-01",
            "endTime": "2024-05-31"
          },
          {
            "name": "2024Q3",
            "startTime": "2024-07-01",
            "endTime": "2024-09-30"
          },
          {
            "name": "2024Q4",
            "startTime": "2024-10-01",
            "endTime": "2024-12-31"
          }
        ],
        "children": [
          {
            "id": 102,
            "label": "自然月",
            "type": "2",
            "parentId": "101",
            "parentName": "自然季",
            "code": "PT1002",
            "name": "自然月",
            "startTime": "2019-01-01",
            "endTime": "2024-12-31",
            "periodSlotList": [
              {
                "name": "2019M1",
                "startTime": "2019-01-01",
                "endTime": "2019-01-31"
              },
              {
                "name": "2019M2",
                "startTime": "2019-02-01",
                "endTime": "2019-02-28"
              },
              {
                "name": "2019M3",
                "startTime": "2019-03-01",
                "endTime": "2019-03-31"
              },
              {
                "name": "2019M4",
                "startTime": "2019-04-01",
                "endTime": "2019-14-30"
              },
              {
                "name": "2019M5",
                "startTime": "2019-05-01",
                "endTime": "2019-05-31"
              },
              {
                "name": "2019M6",
                "startTime": "2019-06-01",
                "endTime": "2019-06-30"
              },
              {
                "name": "2019M7",
                "startTime": "2019-07-01",
                "endTime": "2019-07-31"
              },
              {
                "name": "2019M8",
                "startTime": "2019-08-01",
                "endTime": "2019-08-31"
              },
              {
                "name": "2019M9",
                "startTime": "2019-09-01",
                "endTime": "2019-09-30"
              },
              {
                "name": "2019M10",
                "startTime": "2019-10-01",
                "endTime": "2019-10-31"
              },
              {
                "name": "2019M11",
                "startTime": "2019-11-01",
                "endTime": "2019-11-30"
              },
              {
                "name": "2019M12",
                "startTime": "2019-12-01",
                "endTime": "2019-12-31"
              },
              {
                "name": "2020M1",
                "startTime": "2020-01-01",
                "endTime": "2020-01-31"
              },
              {
                "name": "2020M2",
                "startTime": "2020-02-01",
                "endTime": "2020-02-29"
              },
              {
                "name": "2020M3",
                "startTime": "2020-03-01",
                "endTime": "2020-03-31"
              },
              {
                "name": "2020M4",
                "startTime": "2020-04-01",
                "endTime": "2020-04-30"
              },
              {
                "name": "2020M5",
                "startTime": "2020-05-01",
                "endTime": "2020-05-31"
              },
              {
                "name": "2020M6",
                "startTime": "2020-06-01",
                "endTime": "2020-06-30"
              },
              {
                "name": "2020M7",
                "startTime": "2020-07-01",
                "endTime": "2020-07-31"
              },
              {
                "name": "2020M8",
                "startTime": "2020-08-01",
                "endTime": "2020-08-31"
              }
            ],
            "frequency": "1",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": 200,
    "label": "滚动5年",
    "type": "0",
    "parentId": "",
    "parentName": "",
    "code": "PT200",
    "name": "滚动5年",
    "startTime": "2019-01-01",
    "endTime": "2038-12-31",
    "frequency": "5",
    "periodSlotList": [
      {
        "name": "2019",
        "startTime": "2019-01-01",
        "endTime": "2023-12-31"
      },
      {
        "name": "2024",
        "startTime": "2024-01-01",
        "endTime": "2028-12-31"
      },
      {
        "name": "2029",
        "startTime": "2029-01-01",
        "endTime": "2033-12-31"
      },
      {
        "name": "2034",
        "startTime": "2034-01-01",
        "endTime": "2038-12-31"
      }
    ]
  },
  {
    "id": 300,
    "label": "滚动10年",
    "type": "0",
    "parentId": "",
    "parentName": "",
    "code": "PT300",
    "name": "滚动10年",
    "startTime": "2019-01-01",
    "endTime": "2038-12-31",
    "frequency": "10",
    "periodSlotList": [
      {
        "name": "2019",
        "startTime": "2019-01-01",
        "endTime": "2028-12-31"
      },
      {
        "name": "2029",
        "startTime": "2029-01-01",
        "endTime": "2038-12-31"
      }
    ]
  }
]);
const categoryTreeRef = ref(null);
const single = ref(true);
const multiple = ref(true);
const categoryName = ref("");
const open = ref(false);
const templateData = ref([]);
const loading = ref(true);
const isShowParam = ref(false);
const categoryAndParamList = ref([]);
const templateId = ref("");
const categoryColumns = ref([]);
const categoryParamColumns = ref([]);
const total = ref(0);
const expandedRows = ref([]);
const lastCategoryIndex = ref(0);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const keyfigureCategoryParamAttrList = ref([]);
const templateParamAttrList = ref([]);
const categoryParamVersionOptions = ref(undefined);
const uniqueKey = ref(0);
const openParam = ref(false);
const openParamFile = ref(false);
const checkedKeyfigureCategoryParamAttr = ref([]);
const allParamFilelist = ref([]);
const selectedIds = ref([]);
const showSearch = ref(true);
const fileManage = ref(false);
const merger = ref(true);
const fullImgVisible = ref(false);
const selectedCommonIds = ref([]);
const isAdmin = ref(false);
const openTagParam = ref(false);
const selectPeriodType = ref({});

const dataParam = reactive({
  paramForm: {},
  paramRules: {
    categoryId: [{required: true, message: "类别不能为空", trigger: "blur"}],
    paramName: [{required: true, message: "参数名称不能为空", trigger: "blur"}],
    version: [{required: true, message: "数据版本不能为空", trigger: "blur"}],
  }
});

const {paramForm, paramRules} = toRefs(dataParam);

const findCategoryById = (tree, targetId) => {
  for (const node of tree) {
    if (node.id === targetId) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findCategoryById(node.children, targetId);
      if (found) {
        return found;
      }
    }
  }
  return null; // 如果没有找到，返回null
};

const findMaxId = (tree) => {
  let maxId = 0;

  for (const node of tree) {
    if (node.id > maxId) {
      maxId = node.id;
    }
    if (node.children && node.children.length > 0) {
      const childMaxId = findMaxId(node.children);
      if (childMaxId > maxId) {
        maxId = childMaxId;
      }
    }
  }

  return maxId;
};

const data = reactive({
  form: {},
  fileForm: {},
  periodForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryName: null,
    parentId: null,
    imageUrl: null,
    templateId: null,
    level: null,
    dyParams: {}
  },
  rules: {
    templateId: [{required: true, message: "类别模版不能为空", trigger: "blur"}],
    categoryName: [{required: true, message: "类别名称不能为空", trigger: "blur"}],
    fileCategory: [{required: true, message: "文件类别不能为空", trigger: "blur"}],
  }
});

const {queryParams, form, fileForm, periodForm, rules} = toRefs(data);


const paramFileData = reactive({
  queryFileParam: {
    fileName: null,
  },
  queryCommonFileParam: {},
  fileRules: {}
});

const {queryFileParam, queryCommonFileParam, fileRules} = toRefs(paramFileData);

function reset() {
  // form.value = {
  //   id: null,
  //   type: null,
  //   parentId: null,
  //   parentName: null,
  //   code: null,
  //   name: null,
  //   startTime: null,
  //   endTime: null,
  //   frequency: null,
  //   periodSlotList: []
  // };
  periodForm.value = {
    id: null,
    type: null,
    parentId: null,
    parentName: null,
    code: null,
    name: null,
    startTime: null,
    endTime: null,
    frequency: null,
  };
  //proxy.resetForm("categoryRef");
  //categoryAndParamList.value = [];
}

const tagData = reactive({
  tagForm: {},
  tagRules: {
    tag: [{required: true, message: "基线名称不能为空", trigger: "blur"}],
  }
});

const {tagForm, tagRules} = toRefs(tagData);

function resetTagForm() {
  tagForm.value = {
    tag: null
  };
}

/**
 * 下载附件
 * @param row
 */
function handleDownload(row) {
  const fileName = row.fileName.split('.');
  const fileType = fileName[fileName.length - 1];
  if ('pdf' == fileType) {
    window.open(baseUrl + row.filePath, '_blank');
  } else {
    downloadFile(row.filePath);
  }
}

function handleView(row) {
  const fileName = row.fileName.split('.');
  const fileType = fileName[fileName.length - 1];
  if ('xlsx' === fileType || 'docx' == fileType || 'pdf' == fileType) {
    window.open('officeview?id=' + row.fileId, "_blank");
  } else {
    proxy.$modal.msgError("不支持预览");
  }
}

/**
 * 更新附件
 * @param row
 */
function handleFileUpdate(row) {
  getFilemanage(row.fileId).then(response => {
    fileForm.value = response.data;
    // 将参数附件关系表的id赋值给fileForm（原id是附件表的id）
    fileForm.value.id = row.id
    fileManage.value = true;
    title.value = "修改附件";
  });
}

/**
 * 删除参数文件
 * @param raw
 */
function handleDeleteParamFile(raw) {
  const _ids = raw.id;
  const name = raw.fileName;
  proxy.$modal.confirm('是否确认删除和文件为"' + name + '"的引用关系？').then(function () {
    return deleteParamFile(_ids);
  }).then(() => {
    handleFileQuery();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 新增类别操作 */
function handleAdd() {
  let parentId = selectPeriodType.value.id;
  let parentName = selectPeriodType.value.label;

  reset();

  periodForm.value.parentId = parentId;
  periodForm.value.parentName = parentName;

  open.value = true;
  title.value = "添加期间类型";
}

/** 修改类别操作 */
function handleUpdate() {
  //需要判断一下是否为根节点
  if (!selectPeriodType) {
    proxy.$modal.msgError("请选中期间类型进行修改！");
    return;
  }
  //通过树找到对应的数据
  const foundCategory = findCategoryById(categoryOptions.value, selectPeriodType.value.id);
  if (!foundCategory) {
    return;
  }
  reset();
  open.value = true;
  title.value = "修改期间类型";
  periodForm.value = foundCategory;
  //categoryAndParamList.value = foundCategory.periodSlotList;
}

const removeNodeById = (tree, idToRemove) => {
  tree = tree.filter(node => {
    // 如果当前节点的id与要删除的id不匹配
    if (node.id !== idToRemove) {
      // 如果节点有子节点，则递归地调用removeNodeById来检查子节点
      if (node.children && node.children.length > 0) {
        node.children = removeNodeById(node.children, idToRemove);
      }
      // 返回true以保留当前节点
      return true;
    }
    // 如果当前节点的id与要删除的id匹配，则不返回该节点（即删除它）
    return false;
  });

  return tree;
};

/** 删除类别操作 */
function handleDelete() {
  //需要判断一下是否为根节点
  if (!selectPeriodType) {
    proxy.$modal.msgError("请选中期间类型进行修改！");
    return;
  }
  proxy.$modal.confirm('是否确认删除："' + selectPeriodType.value.label + '"的数据项？').then(function () {
    //从数组总过滤掉
    categoryOptions.value = removeNodeById(categoryOptions.value, selectPeriodType.value.id);
  }).then(() => {
    // getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 查询类别下拉树结构 */
function getCategoryTree() {
  loading.value = false;
}

/** 根据名称筛选类别树 */
watch(categoryName, val => {
  proxy.$refs["categoryTreeRef"].filter(val);
});

/** 节点单击事件 */
function handleNodeClick(data) {
  selectPeriodType.value = data;
  //渲染右侧的表单
  form.value = selectPeriodType.value;
  categoryAndParamList.value = selectPeriodType.value.periodSlotList;
  //点亮修改按钮
  single.value = false;
  multiple.value = false;
}

function getCategoryColumns() {
  let tpid = templateId.value;
  if (!tpid) {
    return;
  }
  categoryColumns.value = [];
  getCategoryColumn(tpid).then(response => {
    for (var i = 1; i < response.data.length - 1; i++) {
      let categoryColumn = {};
      categoryColumn.key = response.data[i].index;
      categoryColumn.prop = response.data[i].columnProp;
      categoryColumn.label = response.data[i].columnLable;
      categoryColumn.visible = true;
      categoryColumn.type = response.data[i].type;
      if (categoryColumn.prop.includes('categoryName') > 0) {
        lastCategoryIndex.value = i - 1;
      }
      categoryColumns.value.push(categoryColumn);
    }
  });
  categoryParamColumns.value = [];
  getCategoryParamColumn(tpid).then(response => {
    for (var i = 1; i < response.data.length; i++) {
      let categoryParamColumn = {};
      categoryParamColumn.index = response.data[i].index;
      categoryParamColumn.prop = response.data[i].columnProp;
      categoryParamColumn.label = response.data[i].columnLable;
      if (response.data[i].type === 'file') {
        categoryParamColumn.width = 150;
      }
      categoryParamColumn.visible = true;
      categoryParamColumn.type = response.data[i].type;
      categoryParamColumns.value.push(categoryParamColumn);
    }
  });


  getCategoryAndParamList();
}

/** 查询类别管理列表 */
function getCategoryAndParamList() {
  isShowParam.value = true;
  loading.value = true;
  queryParams.value.templateId = templateId.value;
  if (selectTree.value && selectTree.value.id === 0) {
    queryParams.value.id = null;
  }
  getCategoryParamList(queryParams.value).then(response => {
    categoryAndParamList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消显示类别弹框按钮
function cancelCategory() {
  open.value = false;
  reset();
}

/**
 * 获取启用的模板列表
 */
function getTemplateData() {
  loading.value = false;
  templateRefList().then(response => {
    templateData.value = [];
    for (var i = 0; i < response.data.length; i++) {
      let templateObj = {};
      templateObj.value = response.data[i].id;
      templateObj.label = response.data[i].templateName;
      templateData.value.push(templateObj);
    }
    // if (!templateId.value) {
    //   templateId.value = response.data.length > 0 ? response.data[0].id : '';
    // }
  });
}

//自定义合并单元格的逻辑
function spanMethod({row, column, rowIndex, columnIndex}) {
  if (!merger.value) {
    return false;
  }
  if (columnIndex > categoryColumns.value.length) {
    return;
  }
  if (expandedRows.value.includes(rowIndex + 1)) {
    return;
  }
  // console.log('row', row, 'column', column, 'rowIndex', rowIndex, 'columnIndex', columnIndex);
  //定义需要合并的列字段，有哪些列需要合并，就自定义添加字段即可
  // 当前行的数据
  const cellValue = row[column.property];

  // 判断只合并定义字段的列数据
  const prevRow = categoryAndParamList.value[rowIndex - 1] //上一行数据
  let nextRow = categoryAndParamList.value[rowIndex + 1] //下一行数据
  // 当上一行的数据等于当前行数据时，当前行单元格隐藏
  if (prevRow && prevRow[column.property] && JSON.stringify(prevRow[column.property]) !== '[]'
      && JSON.stringify(prevRow[column.property]) === JSON.stringify(cellValue) && !expandedRows.value.includes(rowIndex)) {
    return {rowspan: 0, colspan: 0}
  } else {
    // 反之，则循环判断若下一行数据等于当前行数据，则当前行开始进行合并单元格
    let countRowspan = 1 //用于合并计数多少单元格
    while (nextRow && nextRow[column.property] && JSON.stringify(nextRow[column.property]) !== '[]'
    && JSON.stringify(nextRow[column.property]) === JSON.stringify(cellValue)) {
      let next = countRowspan + 1 + rowIndex;
      if (expandedRows.value.includes(next)) {
        break;
      }
      nextRow = categoryAndParamList.value[++countRowspan + rowIndex]
    }
    if (countRowspan > 1) {
      //console.log('countRowspan:' + countRowspan + ';rowIndex:' + rowIndex);
      return {rowspan: countRowspan, colspan: 1}
    }
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleRowClick(row, column, event) {
  // 你可以在这里处理行点击事件，比如加载子数据
  if (row.columnType === 0) {
    return;
  }
  const rowIndex = row.index;
  if (expandedRows.value.includes(rowIndex)) {
    // 如果当前行已经是展开的，则移除它
    expandedRows.value = expandedRows.value.filter(i => i !== rowIndex);
  } else {
    merger.value = false;
    proxy.$refs.categoryTableRef.doLayout();
    // 否则，添加当前行到展开行数组
    expandedRows.value.push(rowIndex);
    merger.value = true;
    proxy.$refs.categoryTableRef.doLayout();
  }
  //console.log("expandedRows:" + expandedRows.value);
}

function cancel() {
  open.value = false;
  reset();
}

function iconHadler({row, rowIndex}) {
  row.index = rowIndex + 1;
  return 'row-expand-unhas';
}

/**
 * 获取图片url
 * @param imagePath
 * @returns {*}
 */
function getImageUrl(imagePath) {
  return baseUrl + imagePath;
}

// 表单重置
function resetParam() {
  paramForm.value = {
    id: null,
    categoryId: null,
    paramName: null,
    coordinateX: null,
    coordinateY: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  keyfigureCategoryParamAttrList.value = [];
  keyfigureCategoryParamAttrList.value = templateParamAttrList.value;
  proxy.resetForm("paramRef");
}

//变更参数版本
function handleChangeVersionParam(row) {
  resetParam();
  const _id = row.id || ids.value;
  let queryParam = {};
  queryParam.id = _id;

  getCategoryParamVersionOptions(_id);

  getCompareVersioInfo(queryParam).then(response => {
    uniqueKey.value += 1;
    paramForm.value = response.data;
    paramForm.value.version = "";
    paramForm.value.versionId = "";
    paramForm.value.version = "V" + (categoryParamVersionOptions.value.length + 2);

    for (var i = 0; i < response.data.keyfigureCategoryParamAttrList.length; i++) {
      response.data.keyfigureCategoryParamAttrList[i].id = "";
      let dictTypeDataArr = [];
      if (response.data.keyfigureCategoryParamAttrList[i].sysDictDataList) {
        for (var j = 0; j < response.data.keyfigureCategoryParamAttrList[i].sysDictDataList.length; j++) {
          let dictTypeData = {};
          dictTypeData.label = response.data.keyfigureCategoryParamAttrList[i].sysDictDataList[j].dictLabel;
          dictTypeData.value = response.data.keyfigureCategoryParamAttrList[i].sysDictDataList[j].dictValue;
          dictTypeDataArr.push(dictTypeData);
        }
      }
      keyfigureCategoryParamAttrList.value = response.data.keyfigureCategoryParamAttrList;
      keyfigureCategoryParamAttrList.value[i].dictTypeData = dictTypeDataArr;
    }
    openParam.value = true;
    title.value = "变更类别参数";
  });
}

function getCategoryParamVersionOptions(categoryParamId) {
  getCategoryParamVersions(categoryParamId).then(response => {
    categoryParamVersionOptions.value = [];
    for (var i = 0; i < response.data.length; i++) {
      let versionParam = {};
      versionParam.value = response.data[i].id;
      versionParam.label = response.data[i].version;
      categoryParamVersionOptions.value.push(versionParam);
    }
  })
}


function rowKeyfigureCategoryParamAttrVersionIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
  if (row.fieldValue !== row.versionValue) {
    return 'highlight-row'; // 返回使该行变红的类名
  }
}

/** 复选框选中数据 */
function handleKeyfigureCategoryParamAttrSelectionChange(selection) {
  checkedKeyfigureCategoryParamAttr.value = selection.map(item => item.index)
}


// 取消按钮
function cancelParam() {
  openParam.value = false;
  resetParam();
}

function submitParamForm() {
  proxy.$refs["paramRef"].validate(valid => {
    if (valid) {
      paramForm.value.keyfigureCategoryParamAttrList = keyfigureCategoryParamAttrList.value;
      if (paramForm.value.id != null) {
        updateParam(paramForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openParam.value = false;
          //重新加载列表
          getCategoryAndParamList();
        });
      } else {
        addParam(paramForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openParam.value = false;
          //重新加载列表
          getCategoryAndParamList();
        });
      }
    }
  });
}

function paramTableExcel(linkTypeId) {
  window.open('luckysheet?id=' + ('excel' + linkTypeId), "_blank");
}

function selectable(row) {
  return row.selectable;
}

function handleUpdateValue(value) {
  // console.log('更新后的值：', value);
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};


function mouseover(data) { // 移入
  data.dropdownShow = true;
}

function mouseout(data) { // 移除
  data.dropdownShow = false;
}

function paramFile(rowData) {
  openParamFile.value = true;
  title.value = "附件管理";
  fileForm.value.categoryId = rowData.id;
  fileForm.value.categoryParamId = rowData.id;
  queryFileParam.value.categoryParamId = rowData.id;
  queryFileParam.value.type = 2;
  handleFileQuery();
}

function rowParamFileIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}


/**
 * 文件多选
 */
function handleSelectionFileChange(selection) {
  fileIds.value = selection.map(item => item.fileId);
}

function resetFile() {
  fileForm.value.id = null;
  fileForm.value.fileId = null;
  fileForm.value.filePath = null;
  fileForm.value.fileCategory = null;
}

function handleAddFile() {
  resetFile();
  fileManage.value = true;
  title.value = "添加附件";
}

/**
 * 按照条件搜索
 */
function handleFileQuery() {
  loading.value = true;
  selectedCommonIds.value = [];
  getAllParamFilelist(queryFileParam.value).then(response => {
    allParamFilelist.value = response.data;
    for (var i = 0; i < response.data.length; i++) {
      if (response.data[i].fileId) {
        selectedCommonIds.value.push(response.data[i].fileId);
      }
    }
    loading.value = false;
  });
}

function resetFileQuery() {
  proxy.resetForm("queryFileRef");
  queryFileParam.value.fileName = "";
  handleFileQuery();
}

function cancelFileAdd() {
  resetFile();
  fileManage.value = false;
}

/**
 * 添加参数附件
 */
function submitFileAdd() {
  // 获取参数类别
  fileForm.value.type = 2;//2=类别
  fileForm.value.categoryParamType = 2;//类别
  if (fileForm.value.id === null) {
    // 上传文件
    addFilemanage(fileForm.value).then(() => {
      proxy.$modal.msgSuccess("新增成功");
      fileManage.value = false;
      // getList();
      handleFileQuery();
    });
  } else {
    // 修改文件
    updateParamFile(fileForm.value).then(() => {
      proxy.$modal.msgSuccess("编辑成功");
      fileManage.value = false;
      // getList();
      handleFileQuery();
    });
  }
}


/**
 * 关闭附件弹框页面
 */
function canceFilelParam() {
  openParamFile.value = false;
  proxy.resetForm("queryFileRef");
  queryFileParam.value.fileName = "";
}


function showFullImage(imagePath) {
  imgUrl.value = baseUrl + imagePath;
  fullImgVisible.value = true;
}

function close() {
  fullImgVisible.value = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {
      if (periodForm.value.id != null) {
        //找到对应的数据进行更新

      } else {
        //新增一个数据
        let periodType = periodForm.value;
        periodType.id = findMaxId(categoryOptions.value) + 1;
        periodType.label = periodType.name;
        if (periodType.parentId) {
          const foundCategory = findCategoryById(categoryOptions.value, periodType.parentId);
          if (!foundCategory.children) {
            foundCategory.children = [];
          }
          foundCategory.children.push(periodType);
        } else {
          categoryOptions.value.push(periodType);
        }
      }
    }
    open.value = false;
  });
}


function generatePeriodSlot() {
  let timeSlot = [];
  let slot1 = {
    id: 1,
    name: 'xxxx',
    startTime: 'xxxxx-xx-xx',
    endTime: 'xxxxx-xx-xx'
  };
  timeSlot.push(slot1);
  categoryAndParamList.value = timeSlot;
}


/**
 *
 * @param categoryParamVersionId
 */
function handleParamVersionChange(categoryParamVersionId) {
  let queryParam = {};
  queryParam.versionId = categoryParamVersionId;
  queryParam.id = paramForm.value.id;
  getCompareVersioInfo(queryParam).then(response => {

    for (var i = 0; i < response.data.keyfigureCategoryParamAttrList.length; i++) {
      if (!paramForm.value.versionId) {
        response.data.keyfigureCategoryParamAttrList[i].id = "";
      }
      let dictTypeDataArr = [];
      if (response.data.keyfigureCategoryParamAttrList[i].sysDictDataList) {
        for (var j = 0; j < response.data.keyfigureCategoryParamAttrList[i].sysDictDataList.length; j++) {
          let dictTypeData = {};
          dictTypeData.label = response.data.keyfigureCategoryParamAttrList[i].sysDictDataList[j].dictLabel;
          dictTypeData.value = response.data.keyfigureCategoryParamAttrList[i].sysDictDataList[j].dictValue;
          dictTypeDataArr.push(dictTypeData);
        }
      }
      keyfigureCategoryParamAttrList.value = response.data.keyfigureCategoryParamAttrList;
      keyfigureCategoryParamAttrList.value[i].dictTypeData = dictTypeDataArr;
    }
  });
}

function paramTable(row, id) {
  if (row.fileType === '0' || row.fileType === '1' || row.fileType === '2') {
    window.open('officeview?id=' + id, "_blank");
  } else {
    downloadFile(row.filePath)
  }
}

/**
 * 是否是管理员
 */
function getInfoRole() {
  getInfo().then(res => {
    const roles = res.roles
    for (var i = 0; i < roles.length; i++) {
      if (roles[i] === 'admin') {
        isAdmin.value = true;
      }
    }
  }).catch(error => {
    proxy.$modal.msgError(error);
  })
}

function makeTag() {
  resetTagForm();
  tagForm.value.tag = formatDate(new Date());
  openTagParam.value = true;
  title.value = "建立基线";
}

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

function cancelTagParam() {
  resetTagForm();
  openTagParam.value = false;
}

function submitTagForm() {
  let viewJson = '{"path":"/keyfigure/param","name":"Param","params":{},"query":{},"hash":"","fullPath":"/keyfigure/param","matched":[{"path":"/keyfigure","redirect":"noRedirect","name":"Keyfigure","meta":{"title":"参数管理","icon":"education","noCache":false,"link":null},"props":{"default":false},"children":[{"name":"Category","path":"category","hidden":false,"meta":{"title":"参数库","icon":"drag","noCache":false,"link":null}},{"name":"Param","path":"param","hidden":false,"meta":{"title":"参数管理","icon":"dashboard","noCache":false,"link":null}},{"name":"Graphical","path":"graphical","hidden":false,"meta":{"title":"统计分析","icon":"chart","noCache":false,"link":null}},{"name":"Filemanage","path":"filemanage","hidden":false,"meta":{"title":"附件管理","icon":"excel","noCache":false,"link":null}},{"name":"Template","path":"template","hidden":false,"meta":{"title":"分类模板","icon":"cascader","noCache":false,"link":null}}],"instances":{"default":{}},"leaveGuards":{},"updateGuards":{},"enterCallbacks":{},"components":{"default":{"__name":"index","__hmrId":"051739fd","__scopeId":"data-v-051739fd","__file":"D:/project/keyfigure-vue/src/layout/index.vue"}}},{"path":"/keyfigure/param","name":"Param","meta":{"title":"参数管理","icon":"dashboard","noCache":false,"link":null},"props":{"default":false},"children":[],"instances":{"default":{}},"leaveGuards":{},"updateGuards":{},"enterCallbacks":{},"components":{"default":{"name":"Category","__hmrId":"62351ec6","__file":"D:/project/keyfigure-vue/src/views/keyfigure/param/index.vue"}}}],"meta":{"title":"参数管理","icon":"dashboard","noCache":false,"link":null},"title":"参数管理"}';
  const view = JSON.parse(viewJson);
  proxy.$refs["tagRef"].validate(valid => {
    if (valid) {
      //提交
      addTag(tagForm.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        openTagParam.value = false;
        //重新加载页面
        proxy.$tab.refreshPage(view);
      });
    }
  });
}


getCategoryTree();
</script>
<style>


.table-container {
  height: 74vh; /* 设置容器高度为视口高度的85% */
  overflow-y: auto; /* 如果内容过多，则启用垂直滚动条 */
  position: relative; /* 为了确保滚动条在容器内部 */
}

.blueText {
  color: blue; /* 设置文本颜色为蓝色 */
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 10px;
  height: 100%;
  /* 其他样式保持不变 */
  position: relative; /* 添加这个属性以便绝对定位的按钮能够相对于这个元素定位 */
  /* 添加以下样式来设置横向滚动 */
  /* max-width: 100%; 假设你想让它在容器宽度内，可根据需要调整 */
  /*overflow-x: auto;  当内容超出宽度时显示横向滚动条 */
  /*white-space: nowrap;  防止文本换行，确保按钮始终在一行内 */
}

.custom-tree-node div {
  /* 假设这是包含附件按钮的div */
  position: absolute; /* 使用绝对定位 */
  right: 10px; /* 距离右侧30px */
  top: 50%; /* 如果需要垂直居中 */
  transform: translateY(-50%); /* 如果需要垂直居中 */
  /* 其他样式保持不变 */
}

/* 如果需要确保附件按钮在内容宽度内不触发横向滚动，可以添加以下样式 */
.custom-tree-node .el-button {
  white-space: nowrap; /* 防止按钮文本换行 */
}

.tree-container {
  width: 100%;
  height: 77vh;
  overflow: auto;
}


.el-table .highlight-row {
  background-color: red;
}

.row-expand-unhas .el-table__expand-column .el-icon {
  visibility: hidden;
}


</style>